import 'widgets/custom_loading_widget.dart';
import 'widgets/custom_toast_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';

import 'config/router_page_name.dart';
import 'config/router_pages.dart';
import 'database/database_helper.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化数据库，但不删除现有数据库
  // 数据库错误处理已经在 DatabaseHelper 中实现
  try {
    await DatabaseHelper.instance.database;
  } catch (e) {
    print('Database initialization error: $e');
  }

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) => _buildMaterialApp(context, child),
    );
  }

  Widget _buildMaterialApp(BuildContext context, Widget? child) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: '乡村振兴APP',
      navigatorObservers: [FlutterSmartDialog.observer],
      builder: (context, home) => _buildSmartDialog(context, home),
      initialRoute: RouterPageName.splashPage,
      getPages: RouterPages.getTeacherPages,
      home: child,
      locale: const Locale('zh'),
      fallbackLocale: const Locale('zh'),
      localizationsDelegates: _localizationsDelegates,
      supportedLocales: const [Locale('zh')],
    );
  }

  Widget _buildSmartDialog(BuildContext context, Widget? home) {
    return FlutterSmartDialog.init(
      toastBuilder: (msg) => CustomToastWidget(msg: msg),
      loadingBuilder: (msg) => const CustomLoadingWidget(msg: '加载中'),
      builder: (context, home) => _buildGestureDetector(context, home),
    )(context, home);
  }

  Widget _buildGestureDetector(BuildContext context, Widget? home) {
    return MediaQuery(
      data: MediaQuery.of(context).copyWith(
        textScaler: const TextScaler.linear(1.0),
      ),
      child: GestureDetector(
        child: home ?? const SizedBox(),
        onTap: () => _handleTap(context),
      ),
    );
  }

  void _handleTap(BuildContext context) {
    final currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  static const _localizationsDelegates = [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ];
}

